/*
 * Mark O'Meara
 * 08332240
 * CS4032 - Dist. Sys.
 * Due: 19/12/12
 */

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.rmi.RemoteException;
import java.rmi.server.RemoteServer;
import java.rmi.server.ServerNotActiveException;
import java.rmi.server.UnicastRemoteObject;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AuthenticationService extends UnicastRemoteObject implements AuthenticationServiceInterface {

	private static final String ALGORITHM = "AES";
	
	//Col 1 = IP address (ie client ID), Col 2 = Key (or client password?)
	String users[][];
	//Needs to be 16, 24 or 32 bytes
	byte[] tgs_secret;
	
	
	/*Need to remember that more than one 
	 * service may be running on the same
	 * IP aadress
	 */
	String serverkeys[][];
	public AuthenticationService() throws RemoteException {
	//	super();
		tgs_secret = new byte[] {'M','y',' ','s','u','p','e','r',' ','a','m','a','z','i','n','g',' ','s','e','c'
				,'r','e','t',' ','T','G','S',' ','k','e','y','!'};
		users = new String[1][];
		users[0] = new String[2];
		users[0][0] = "sampleusername";
		users[0][1] = "samplepassword";
	}
	
	/*[0]: HASHKEY(Sessionkey), [1]: HASHKEY( TGS_SECRET( ClientID)), [2]: HASHKEY( TGS_SECRET(  Sessionkey ) )
	 * First row will be session key
	 * Second and third row will be ticket encrypted with tgs secret key
	 * Second row is client ID
	 * Third row will be session key
	 * every row will be encrypted with client password hash
	 */
	public String[] getSession(String clientID) throws RemoteException{
		try{
			String userpass = findUserPass(clientID);
			byte[] hashkey = getKey(userpass);
			String sessionkey = createSessionKey();
			
			String[] res = new String[3];
			res[0] = encrypt(sessionkey, hashkey);
			res[1] = encrypt(encrypt(clientID, tgs_secret), hashkey);
			//Session key encrypted with tgs secret and then client's hash/password key
			res[2] = encrypt(encrypt(sessionkey, tgs_secret), hashkey);
			System.out.println("Returning Session Key: " + sessionkey);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
		
	//IF client is in DB:
	//1. Hash client's password
	//2. Return generated Client/TGS session key encr with client hash (above)
	//3. Return TGS Ticket (Incl. client ID, client net address, ticket validity period, client/TGS sess. key)
	//Encrypted using TGS secret key

	public String findUserPass(String clientID){
		int i;
		for(i = 0; i < users.length && !users[i][0].equals(clientID); i++){	
		}
		if(i < users.length)
			return users[i][1];
		else
			return null;
	}
	
	private byte[] getKey(String userpass){
		MessageDigest cript;
		try {
			cript = MessageDigest.getInstance("SHA-1");
			cript.reset();
			cript.update(userpass.getBytes("utf8"));
			//This will give a 20byte key, but we need to pad out to 24byte
			byte[] key_20byte = cript.digest();
			byte[] hashkey = new byte[24];
			int n;
			for(n = 0; n < 20; n++){
				hashkey[n] = key_20byte[n];
			}
			for(;n < 24; n++){
				hashkey[n] = 'A';
			}
			return hashkey;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String createSessionKey(){
		Random generator = new Random();
	
		byte[] res = new byte[32];
		
		//Create random session key, 32 bytes long
		Integer r;
		for(int i = 0; i < res.length; i++ ){	
			r = generator.nextInt(94) + 32; //Keeps it to readable bytes
			res[i] = r.byteValue();
		}
		String result = new BASE64Encoder().encode(res);
		return result;
	}
	
	private String encrypt(String msg, byte[] keyValue) throws Exception{
		Key key = new SecretKeySpec(keyValue, ALGORITHM);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(Cipher.ENCRYPT_MODE, key);
		
		String valueToEnc = msg;
		byte[] encValue = c.doFinal(new BASE64Decoder().decodeBuffer(valueToEnc));
		String eValue = new BASE64Encoder().encode(encValue);
		return eValue;
	}
	
	private String decrypt(String msg, byte[] keyValue) throws Exception{
		Key key = new SecretKeySpec(keyValue, ALGORITHM);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(Cipher.DECRYPT_MODE, key);
		
		byte[] decordedValue = new BASE64Decoder().decodeBuffer(msg);
		byte[] decValue = c.doFinal(decordedValue);
		String dValue = new String(decValue);
		return dValue;
	}

}
